package Niuke.剑指offer;

import domain.ListNode;

/**
 * @author: leiwenkang
 * @date: 2020/6/14
 * @time: 23:15
 */
public class 有环链表的入口 {
    public static void main(String[] args) {
        ListNode p1 = new ListNode(1);
        ListNode p2 = new ListNode(2);
        ListNode p3 = new ListNode(3);
        ListNode p4 = new ListNode(4);
        ListNode p5 = new ListNode(5);
        p1.next = p2;
        p2.next = p3;
        p3.next = p4;
        p4.next = p5;
        p5.next = p3;
        ListNode result = EntryNodeOfLoop(p1);
        System.out.println(result.val);
    }

    public static ListNode EntryNodeOfLoop(ListNode pHead){
        if (pHead == null) {
            return null;
        }

        ListNode slow = pHead;
        ListNode fast = pHead;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                break;
            }
        }

        if (fast == null || fast.next == null) {
            return null;
        }

        slow = pHead;
        while (slow != fast) {
            slow = slow.next;
            fast = fast.next;
        }
        return slow;
    }
}
